﻿var PageControl = {
    /**
     * 查询字段
     * ControlType(控件类型) ,0 - Text ，1 - Select，2 - datetime
     * Operator，
        0 - 数字、日期对比 "=", "!=", ">", ">=", "<", "<="
        1 - 模糊查询 "包含", "不包含", "=", "!="
        2 - 值为select选择的，如性别、婚姻状况 "=", "!="
        3 - 值为select选择的，但只能 "="，如：省、市、区、职位、职等、分公司、部门等字段。。。
     */
    Filds: [
        { "Name": "员工姓名", "ControlType": 0, "Operator": 1 },
        { "Name": "年龄", "ControlType": 0, "Operator": 0 },
        { "Name": "出生日期", "ControlType": 2, "Operator": 0 },
        { "Name": "职位", "ControlType": 1, "Operator": 2 },
        { "Name": "工号", "ControlType": 0, "Operator": 1 },
        { "Name": "籍贯", "ControlType": 1, "Operator": 2 },
    ],
    /**
     * 字段操作类型（用于操作符下拉框）
     */
    FieldOperate: [
        {
            "OperateType": 0,
            "Operators": [
                { "Text": "=", "Value": "eq" },
                { "Text": "!=", "Value": "ne" },
                { "Text": ">", "Value": "gt" },
                { "Text": ">=", "Value": "ge" },
                { "Text": "<", "Value": "lt" },
                { "Text": "<=", "Value": "le" }
            ]
        },
        {
            "OperateType": 1,
            "Operators": [
                { "Text": "包含", "Value": "include" },
                { "Text": "不包含", "Value": "notinclude" },
                { "Text": "=", "Value": "eq" },
                { "Text": "!=", "Value": "ne" }]
        },
        {
            "OperateType": 2,
            "Operators": [
                { "Text": "=", "Value": "eq" },
                { "Text": "!=", "Value": "ne" }]
        },
        {
            "OperateType": 3,
            "Operators": [
                { "Text": "=", "Value": "eq" }
            ]
        },
    ],
    /**
     * 删除当前查询条件
     */
    RemoveCondition: function (obj) {
        $(obj).parent().remove();
    },
    /**
      * 添加查询条件
      */
    AddCondition: function () {
        var htmlArr = new Array();
        htmlArr.push(`
        <div class="form-inline input-table">
            <div class="input-group">
                <label class="input-group-addon">关系</label>
                <select name="logic" class="form-control">
                    <option value="and">并且</option>
                    <option value="or">或者</option>
                </select>
            </div>

            <div class="input-group">
                <label class="input-group-addon">字段名</label>
                <select name="field" class="form-control filed">
                    <option Value="">请选择</option>`);

        //对查询字段进行遍历，添加至下拉列表中
        $.each(PageControl.Filds, function (index, item) {
            htmlArr.push(`<option ControlType="${item.ControlType}" Operator="${item.Operator}" "Value"="${item.Name}">${item.Name}</option>`)
        });
        htmlArr.push(`
                </select>
            </div>
            <div class="input-group">
                <label class="input-group-addon">操作符</label>
                <select name="operation" class="form-control operate">
                    <option value="">请选择</option>
                </select>
            </div>
            <div class="input-group">
                <label class="input-group-addon">输入</label>
                <input type="text" name="inputValue" class="form-control inputvalue" placeholder="请输入对比的值" />
                <input type="date" name="inputValue" class="form-control inputvalue hidden date" placeholder="请选择日期" />
                <select name="inputValue" class="form-control hidden inputvalue select"><option Value="">请选择</option></select>
            </div>
            <button class="btn btn-danger">
                删除
            </button>
        </div >            
            `);
        //添加查询条件结束
        $("#divConditions").append(htmlArr.join(''))
    },
    ConditionsArray: null,
    /**
     * 获取查询条件，并设置至PageControl.ConditionArray
     */
    FillSearchCondition: function () {
        var flag = true;
        PageControl.ConditionsArray = new Array();
        var Relation, Field, operation, inputValue, OperatorType, ValueType;
        $("#divConditions>div").each(function (index, elem) {
            var $this = $(elem);
            Relation = $this.find("[name='logic']").val();//关系
            Field = $this.find("[name='field']").val();//字段
            operation = $this.find("[name='operation']").val();//运算符
            inputValue = $this.find("[name='inputValue']:visible").val();//值
            if (Field == "") {
                alert('请选择需要查询的字段');
                flag = false;
                return false;
            }
            if (inputValue == "") {
                alert(`请输入(选择) ${Field} 的值`);
                flag = false;
                return false;
            }
            //if (Field == "籍贯") {
            //    inputValue = $this.find("[name='Val']").val();//值
            //}
            //OperatorType = $this.find("[name='Operator']").attr("OperatorType");//运算类型可包含哪些
            //ValueType = $this.find("[name='Val']:visible").attr("ValueType");
            var condition = {
                "Relation": Relation,
                "Field": Field,
                "Operation": operation,
                "InputValue": inputValue,
                //"OperatorType": OperatorType,
                //"ValueType": ValueType
            };
            PageControl.ConditionsArray.push(condition);
        });
        return flag;
        console.log(JSON.stringify(PageControl.ConditionsArray));
    },
};

$(document).ready(function () {
    //新增查询条件
    $("#btnAdd").on("click", function () {
        PageControl.AddCondition();
    });

    //清空查询条件
    $("#btnClear").on("click", function () {
        $("#divConditions").empty();
    });

    //查询
    $("#btnSearch").on("click", function () {
        if ($("#divConditions").children().length == 0) {
            alert('请添加查询条件');
            return;
        }
        var flag = PageControl.FillSearchCondition();
        if (!flag) {
            return;
        }
        $.ajax({
            url: "/home/search",
            data: JSON.stringify(PageControl.ConditionsArray),
            type: "POST",
            contentType: "application/json;utf-8",
            success: function (data) {
                $("#usersTable").DataTable({
                    data: data, paging: false, destroy: true, searching: false, ordering: false,
                    oLanguage: {
                        "sInfo": "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",
                        "sInfoEmpty": "没有记录",
                        "sZeroRecords": "没有找到数据",
                    },
                    columns: [
                        { data: "RealName", title: "姓名" },
                        { data: "JobNumber", title: "工号" },
                        { data: "Age", title: "年龄" },
                        { data: "BirthdayStr", title: "生日" },
                        { data: "JobPosition", title: "职位" },
                        { data: "ProvinceName", title: "省" },
                        { data: "CityName", title: "市" },
                    ]
                });
            },
            error: function () {

            }
        })

    });

    //字段改变事件
    $("#divConditions").on("change", ".filed", function () {
        var $this = $(this);
        var option = $this.find(":selected");
        var selectedFieldName = option.val();
        if (selectedFieldName != '') {
            //操作类型
            var operatorType = option.attr("Operator");
            //控件类型
            var controlType = option.attr("ControlType");
            //单个条件根节点 div
            var $conditionRootNode = $this.parents(".input-table")
            //操作符下拉列表控件
            var $operateControl = $conditionRootNode.find(".operate");
            $operateControl.empty();//字段改变，清空操作符下拉列表后动态添加
            $.each(PageControl.FieldOperate[operatorType].Operators, function (index, item) {
                $operateControl.append(`<option value="${item.Value}">${item.Text}</option>`)
            });
            //输入框 ControlType(控件类型) ,0 - Text ，1 - Select，2 - datetime
            if (controlType == 0) {
                $conditionRootNode.find(".inputvalue").addClass("hidden");
                $conditionRootNode.find(".inputvalue:text").removeClass("hidden");
            } else if (controlType == 1) {
                $conditionRootNode.find(".inputvalue").addClass("hidden");
                $conditionRootNode.find(".select").removeClass("hidden");
            }
            else if (controlType == 2) {
                $conditionRootNode.find(".inputvalue").addClass("hidden");
                $conditionRootNode.find(".date").removeClass("hidden");
            }

        } else {
            //清空后面 操作符的值 及 输入的值
        }
    });

    //删除当前查询条件
    $("#divConditions").on("click", ".btn-danger", function () {
        PageControl.RemoveCondition(this)
    })

});